package com.glwan.fixedassetapp.helper;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.KeyEvent;

import com.glwan.fixedassetapp.handler.ReaderResponseInterfaces;

public class KeyCodeReceiver {

    private static final String TAG = "KeyCodeReceiver";
    private static KeyCodeReceiver keyCodeReceiver;
    KeyReceiver keyReceiver;
    Activity activity;

    private KeyCodeReceiver() {

    }

    public static KeyCodeReceiver getInstance(Activity activity) {
//        if(keyCodeReceiver == null){
        keyCodeReceiver = new KeyCodeReceiver();
//        }
        keyCodeReceiver.activity = activity;
        return keyCodeReceiver;
    }

    public void registerKeyCodeReceiver() {
        keyReceiver = new KeyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.rfid.FUN_KEY");
        filter.addAction("android.intent.action.FUN_KEY");
        activity.registerReceiver(keyReceiver, filter);
    }

    public void unregisterReceiver() {
        activity.unregisterReceiver(keyReceiver);
    }


    //
    private class KeyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int keyCode = intent.getIntExtra("keyCode", 0);
            Log.e(TAG, "keyCode = " + keyCode);
            if (keyCode == 0) {
                keyCode = intent.getIntExtra("keycode", 0);
            }
            boolean keyDown = intent.getBooleanExtra("keydown", false);
            if (keyDown) {
//                ToastUtils.showText("KeyReceiver:keyCode = down" + keyCode);
            } else {
//                ToastUtils.showText("KeyReceiver:keyCode = up" + keyCode);
                switch (keyCode) {
                    case KeyEvent.KEYCODE_F1:
                    case KeyEvent.KEYCODE_F2:
                    case KeyEvent.KEYCODE_F5:
                        break;
                    case KeyEvent.KEYCODE_F3://C510x
                    case KeyEvent.KEYCODE_F4://6100
                    case KeyEvent.KEYCODE_F7://H3100
                        if (activity instanceof ReaderResponseInterfaces.ResponseKeyEventHandler) {
                            ((ReaderResponseInterfaces.ResponseKeyEventHandler) activity).handleResponse();
                        }
                        break;
                }
            }
        }

    }
}
